package com.wzq.device.config;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.wzq.controller.admin.GetSome;
import com.wzq.dao.pojo.P_parameters;
import com.wzq.dao.pojo.Project;
import com.wzq.util.StringUtil;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.integration.channel.DirectChannel;
import org.springframework.integration.core.MessageProducer;
import org.springframework.integration.mqtt.core.DefaultMqttPahoClientFactory;
import org.springframework.integration.mqtt.core.MqttPahoClientFactory;
import org.springframework.integration.mqtt.inbound.MqttPahoMessageDrivenChannelAdapter;
import org.springframework.integration.mqtt.support.DefaultPahoMessageConverter;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessageHandler;
import org.springframework.messaging.MessagingException;

import java.util.Map;

/**
 * @Author: zlh
 * @Description: 消息订阅配置
 */
@Configuration
public class IotMqttSubscriberConfig extends GetSome {
    @Autowired
    private MqttConfig mqttConfig;
    @Autowired
    private IotMqttGateway mqttGateway;


    @Bean
    public MqttPahoClientFactory mqttClientFactory() {
        DefaultMqttPahoClientFactory factory = new DefaultMqttPahoClientFactory();
//        factory.setServerURIs(mqttConfig.getServers());
        MqttConnectOptions options = new MqttConnectOptions();
        options.setUserName(mqttConfig.getUserName());
        options.setPassword(mqttConfig.getPassword().toCharArray());
        options.setServerURIs(new String[]{mqttConfig.getServers()});
        factory.setConnectionOptions(options);
        return factory;
    }

    @Bean
    public MessageChannel iotMqttInputChannel1() {
        return new DirectChannel();
    }

    @Bean
    public MessageProducer inbound() {
        MqttPahoMessageDrivenChannelAdapter adapter = new MqttPahoMessageDrivenChannelAdapter(mqttConfig.getClientId(), mqttClientFactory(), mqttConfig.getDefaultTopic());
        adapter.setCompletionTimeout(1000);
        adapter.setConverter(new DefaultPahoMessageConverter());
        adapter.setQos(0);
        adapter.setOutputChannel(iotMqttInputChannel1());
        return adapter;
    }

    /**
     * @author zlh
     * @description 消息订阅
     */
    @Bean
    @ServiceActivator(inputChannel = "iotMqttInputChannel1")
    public MessageHandler handlerTest() {
        return message -> {
            try {
                //智能开关等硬件通讯代码写在此处 to pzm

                String topic = message.getHeaders().get("mqtt_receivedTopic").toString();//路径
                String topictmp = topic;  //topictmp为原topic的副本
                System.out.println("接受到的主题为：" + topic);
                topic = topic.replace("/v1", "/v2");
                String mess = message.getPayload().toString();//数据
                Map<String, Object> messMap = StringUtil.mapString(mess);//map类型的mess
                System.out.println(messMap.toString());
                System.out.println("接收到消息---：" + mess);

                //提取路径
                String[] split = topictmp.split("/");
                String device = split[2]; //设备类型
                System.out.println(device);
                String device_id = split[3]; //设备id
                String state = "/";
                for (int i = 4; i < split.length; i++) {
                    state += split[i];
                    if (i != split.length - 1) {
                        state += "/";
                    }
                }
                //提取p_id
                LambdaQueryWrapper<Project> lqw = new LambdaQueryWrapper<Project>();
                lqw.eq(Project::getTitle, device_id).eq(Project::getType, getType_id(device));
                int p_id = iProjectService.getOne(lqw).getId();

                P_parameters p_parameters = new P_parameters();
                switch (state) {
                    case "/login":
                        //region
                        if (device.equals("smart_socket")) {
                            Object login_state = messMap.get("login_state");
                            Object switch1_state = messMap.get("switch1_state");
                            Object switch2_state = messMap.get("switch2_state");

                            p_parameters.setLogin_state(login_state.toString().equals("1"));
                            p_parameters.setSwitch1_state(switch1_state.equals("1"));
                            p_parameters.setSwitch2_state(switch2_state.equals("1"));
                            p_parameters.setP_id(p_id);
                            boolean update = ip_parametersService.update(p_parameters, new LambdaUpdateWrapper<P_parameters>().eq(P_parameters::getP_id, p_id));
                            if (update) {
                                mess = "“login_state”:1";
                            } else {
                                mess = "“login_state”:0";
                            }
                            mqttGateway.sendMessage2Mqtt(mess, topic + "/rsp");
                        } else if (device.equals("smart_lamp")) {
                            p_parameters.setP_id(p_id);
                            p_parameters.setLogin_state(messMap.get("login_state").toString().equals("1"));
                            p_parameters.setLamp_state(messMap.get("lamp_state").toString().equals("1"));
                            boolean update = ip_parametersService.update(p_parameters, new LambdaUpdateWrapper<P_parameters>().eq(P_parameters::getP_id, p_id));
                            if (update) {
                                mess = "“login_state”:1";
                            } else {
                                mess = "“login_state”:0";
                            }
                            mqttGateway.sendMessage2Mqtt(mess, topic + "/rsp");
                        }
                        break;
                    case "/con/rsp":
                        //控制指令响应
                        System.out.println("控制指令响应");
                        if (device.equals("smart_socket")) {
                            p_parameters.setElectricity(Double.valueOf(messMap.get("electricity").toString()));
                            p_parameters.setCurrent(Double.valueOf(messMap.get("current").toString()));
                            p_parameters.setVoltage(Double.valueOf(messMap.get("voltage").toString()));
                            p_parameters.setSwitch1_state( messMap.get("switch1_state").equals("1"));
                            p_parameters.setSwitch2_state(messMap.get("switch2_state").equals("1"));
                            p_parameters.setP_id(p_id);
                            P_parameters old = ip_parametersService.getOne(new LambdaQueryWrapper<P_parameters>().eq(P_parameters::getP_id, p_id));
                            if ((old.getSwitch1_state().equals(p_parameters.getSwitch1_state()))&& (old.getSwitch2_state().equals(p_parameters.getSwitch2_state()))) {
                                System.out.println("ok");
                            }
                            else {
                                System.out.println("给管理员发消息");
                            }
                            ip_parametersService.update(p_parameters, new LambdaUpdateWrapper<P_parameters>().eq(P_parameters::getP_id, p_id));
//                        Thread.currentThread().notifyAll();
                        }
                        else if(device.equals("smart_lamp")){
                            p_parameters.setP_id(p_id);
                            p_parameters.setLamp_state(messMap.get("lamp_state").equals("1"));
                            P_parameters old = ip_parametersService.getOne(new LambdaQueryWrapper<P_parameters>().eq(P_parameters::getP_id, p_id));
                            if (old.getLamp_state().equals(p_parameters.getLamp_state())) {
                                System.out.println("ok");
                            }
                            else {
                                System.out.println("给管理员发消息");
                            }
                            ip_parametersService.update(p_parameters, new LambdaUpdateWrapper<P_parameters>().eq(P_parameters::getP_id, p_id));
                        }
                        //查数据库里指令状态
                        break;
                    case "/data/heartbeat":
                        //!!  心跳包
                        if(device.equals("smart_socket")){
                            p_parameters.setElectricity(Double.valueOf(messMap.get("electricity").toString()));
                            p_parameters.setCurrent(Double.valueOf(messMap.get("current").toString()));
                            p_parameters.setVoltage(Double.valueOf(messMap.get("voltage").toString()));
                            p_parameters.setSwitch1_state(messMap.get("switch1_state").toString().equals("1"));
                            p_parameters.setSwitch2_state(messMap.get("switch2_state").toString().equals("1"));
                            p_parameters.setP_id(p_id);
                            boolean update = ip_parametersService.update(p_parameters, new LambdaUpdateWrapper<P_parameters>().eq(P_parameters::getP_id, p_id));
                            if (update) {
                                mess = "“state”:1";
                            } else {
                                mess = "“state”:0";
                            }
                            mqttGateway.sendMessage2Mqtt(mess, topic + "/rsp");
                        }
                        else if(device.equals("smart_lamp")){
                            p_parameters.setP_id(p_id);
                            p_parameters.setLamp_state(messMap.get("lamp_state").toString().equals("1"));
                            boolean update = ip_parametersService.update(p_parameters, new LambdaUpdateWrapper<P_parameters>().eq(P_parameters::getP_id, p_id));
                            if (update) {
                                mess = "“state”:1";
                            } else {
                                mess = "“state”:0";
                            }
                            mqttGateway.sendMessage2Mqtt(mess, topic + "/rsp");
                        }
                        break;
                    case "/manual_con/config/rsp":
                        //手动操作开关功能设置响应
                        if(device.equals("smart_socket")){
                            p_parameters.setP_id(p_id);
                            p_parameters.setManual_state(messMap.get("manual_state").toString().equals("1"));
                            boolean update = ip_parametersService.update(p_parameters, new LambdaUpdateWrapper<P_parameters>().eq(P_parameters::getP_id, p_id));
                            if(update){
                                System.out.println("修改成功");
                            }else{
                                System.out.println("修改失败");
                            }
                        }
                        else if(device.equals("smart_lamp")){

                        }

                        break;
                    case "/clear_electricity/rsp":
                        //累积用电清零响应
                        System.out.println("累积用电清零响应");
                        if(messMap.get("clear_con").toString().equals("1")){
                            p_parameters.setP_id(p_id);
                            p_parameters.setElectricity(Double.valueOf(0));
                            boolean update= ip_parametersService.update(p_parameters, new LambdaUpdateWrapper<P_parameters>().eq(P_parameters::getP_id, p_id));
                            if(update){
                                System.out.println("修改成功");
                            }else{
                                System.out.println("修改失败");
                            }
                        }
                        break;
                    case "/manual_con":
                        //手动操作状态上报
                        System.out.println("手动操作状态上报");
                        if(device.equals("smart_socket")) {
                            p_parameters.setP_id(p_id);
                            p_parameters.setElectricity(Double.valueOf(messMap.get("electricity").toString()));
                            p_parameters.setCurrent(Double.valueOf(messMap.get("current").toString()));
                            p_parameters.setVoltage(Double.valueOf(messMap.get("voltage").toString()));
                            p_parameters.setSwitch1_state(messMap.get("switch1_state").equals("1"));
                            p_parameters.setSwitch2_state(messMap.get("switch2_state").equals("1"));
                            boolean update =ip_parametersService.update(p_parameters,new LambdaUpdateWrapper<P_parameters>().eq(P_parameters::getP_id,p_id));
                            if (update) {
                                mess = "“state”:1";
                            } else {
                                mess = "“state”:0";
                            }
                            mqttGateway.sendMessage2Mqtt(mess, topic + "/rsp");
                        }
                        else if(device.equals("smart_lamp")){
                            p_parameters.setP_id(p_id);
                            p_parameters.setLamp_state(messMap.get("lamp_state").equals("1"));
                            boolean update =ip_parametersService.update(p_parameters,new LambdaUpdateWrapper<P_parameters>().eq(P_parameters::getP_id,p_id));
                            if (update) {
                                mess = "“state”:1";
                            } else {
                                mess = "“state”:0";
                            }
                            mqttGateway.sendMessage2Mqtt(mess, topic + "/rsp");
                        }
                        break;
                    case "/read_state/rsp":
                        //查询状态响应
                        System.out.println("查询状态响应");
                        if(device.equals("smart_socket")) {
                            p_parameters.setP_id(p_id);
                            p_parameters.setElectricity(Double.valueOf(messMap.get("electricity").toString()));
                            p_parameters.setCurrent(Double.valueOf(messMap.get("current").toString()));
                            p_parameters.setVoltage(Double.valueOf(messMap.get("voltage").toString()));
                            p_parameters.setSwitch1_state(messMap.get("switch1_state").equals("1"));
                            p_parameters.setSwitch2_state(messMap.get("switch2_state").equals("1"));
                            boolean update =ip_parametersService.update(p_parameters,new LambdaUpdateWrapper<P_parameters>().eq(P_parameters::getP_id,p_id));
                            if (update) {
                                System.out.println("查询成功");
                            } else {
                                System.out.println("查询失败");
                            }

                        }
                        else if(device.equals("smart_lamp")){
                            p_parameters.setP_id(p_id);
                            p_parameters.setLamp_state(messMap.get("lamp_state").equals("1"));
                            boolean update =ip_parametersService.update(p_parameters,new LambdaUpdateWrapper<P_parameters>().eq(P_parameters::getP_id,p_id));
                            if (update) {
                                System.out.println("查询成功");
                            } else {
                                System.out.println("查询失败");
                            }

                        }
                        break;


                }



            } catch (MessagingException ex) {
//                logger.info(ex.getMessage());
                System.out.println(ex.getMessage());
            }
        };

    }

    public String sendMess(String data, String topic) {
        mqttGateway.sendMessage2Mqtt(data, topic);
        return "success";
    }


}


